package tech.xs.auth.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import tech.xs.auth.api.domain.bo.path.EditAuthPathPermissionBo;
import tech.xs.auth.domain.entity.AuthPathPermission;
import tech.xs.auth.domain.exception.AuthException;
import tech.xs.auth.service.AuthPathPermissionService;
import tech.xs.auth.service.AuthPathService;
import tech.xs.common.framework.domain.enums.DataSourceTypeEnum;
import tech.xs.common.framework.domain.model.ApiResult;

import javax.annotation.Resource;

@Slf4j
@Validated
@RestController
@RequestMapping("/path/permission")
public class AuthPathPermissionController {

    @Resource
    private AuthPathPermissionService authPathPermissionService;
    @Resource
    private AuthPathService authPathService;

    @GetMapping("/isUsedPermissionCode")
    public ApiResult<Boolean> isPathAuth(@RequestParam String permissionCode) {
        if (StrUtil.isBlank(permissionCode)) {
            throw new AuthException("permissionCode 不能为空");
        }
        long count = authPathPermissionService.count(Wrappers.<AuthPathPermission>lambdaQuery().eq(AuthPathPermission::getPermissionCode, permissionCode));
        return ApiResult.success(count > 0);
    }

    @PostMapping("/update/byPermissionCode")
    public ApiResult<Void> updateByPermissionCode(@RequestBody EditAuthPathPermissionBo bo) {
        authPathPermissionService.update(Wrappers.<AuthPathPermission>lambdaUpdate()
                .set(bo.getStatus() != null, AuthPathPermission::getStatus, bo.getStatus())
                .ne(AuthPathPermission::getSource, DataSourceTypeEnum.SystemGeneration)
                .eq(AuthPathPermission::getPermissionCode, bo.getPermissionCode()));
        authPathService.reloadAllAuthPathCache();
        return ApiResult.success();
    }

}
